<template>
  <div class="h-full flex flex-col">
    <!-- 标签栏 -->
    <div class="flex bg-[#252526] border-b border-[#323232]">
      <div
        v-for="tab in tabs"
        :key="tab.id"
        @click="$emit('switch-tab', tab.id)"
        class="px-4 py-2 flex items-center space-x-2 cursor-pointer border-r border-[#323232] group"
        :class="[
          currentTab === tab.id 
            ? 'bg-[#1E1E1E] text-white' 
            : 'text-[#969696] hover:bg-[#2D2D2D]'
        ]"
      >
        <span class="text-sm">{{ tab.name }}</span>
        <button
          @click.stop="$emit('close-tab', tab.id)"
          class="opacity-0 group-hover:opacity-100 hover:text-white transition-opacity"
        >
          ×
        </button>
      </div>
    </div>

    <!-- 编辑器区域 -->
    <div class="flex-1 bg-[#1E1E1E]">
      <CodeEditor
        v-if="currentTab"
        :key="currentTab"
        :content="getCurrentContent()"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import CodeEditor from './CodeEditor.vue'

const props = defineProps({
  tabs: {
    type: Array,
    required: true
  },
  currentTab: {
    type: [Number, null],
    required: true
  }
})

defineEmits(['switch-tab', 'close-tab'])

// 示例文件内容
const fileContents = {
  'App.vue': `<template>
  <div class="app">
    <header>
      <h1>{{ title }}</h1>
      <button @click="count++">
        Count: {{ count }}
      </button>
    </header>
    <main>
      <p>Welcome to Vue!</p>
    </main>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const title = ref('Vue App')
const count = ref(0)
<\/script>`,

  'main.js': `import { createApp } from 'vue'
import App from './App.vue'
import './style.css'

const app = createApp(App)

app.mount('#app')

// Global error handler
app.config.errorHandler = (err) => {
  console.error('Global error:', err)
}`
}

// 获取当前标签页的内容
const getCurrentContent = () => {
  const tab = props.tabs.find(t => t.id === props.currentTab)
  return tab?.content || ''
}

// 添加新标签页
const addTab = (filename) => {
  // 检查是否已存在相同文件名的标签
  const existingTab = props.tabs.find(tab => tab.name === filename)
  
  if (existingTab) {
    // 如果已存在，只切换到该标签
    props.currentTab = existingTab.id
    return
  }

  // 如果不存在，创建新标签
  const newTab = {
    id: Date.now(),
    name: filename,
    content: fileContents[filename] || `// ${filename}\n`
  }
  props.tabs.push(newTab)
  props.currentTab = newTab.id
}

// 切换标签页
const switchTab = (id) => {
  props.currentTab = id
}

// 关闭标签页
const closeTab = (id) => {
  const index = props.tabs.findIndex(t => t.id === id)
  if (index !== -1) {
    props.tabs.splice(index, 1)
    if (props.currentTab === id) {
      props.currentTab = props.tabs[index - 1]?.id || props.tabs[0]?.id || null
    }
  }
}

defineExpose({
  addTab
})
</script> 